import { getEmployeeList } from '../../api/employee';
import { addAttendance, updateEmployee } from '../../api/attendance';
import { getAllSubProjectList, fetchSubProjectEmployees } from '../../api/project'; // 添加获取项目列表的接口

Page({
  data: {
    date: '选择日期', // 默认日期显示
    subprojectList: [], // 小项目列表
    selectedProjectId: null, // 选中的小项目ID
    selectedProjectName: '', // 选中的小项目名称
    staffList: [], // 已选择的员工列表
    allEmployees: [], // 所有员工列表
    tabActive: 'attendance', // 当前活跃的标签页
    shift: '', // 班次
    overtime: '无加班', // 加班状态
    overtimeHours: '', // 加班时长
    remark: '', // 备注
    recordedList: [], // 已记录的考勤列表
    showAddModal: false, // 控制添加员工弹窗的显示
    showRemoveModal: false // 控制删除员工弹窗的显示
  },

  // 页面加载时调用，加载项目列表
  onLoad() {
    this.loadProjectList();
  },

  // 加载项目列表
  loadProjectList() {
    getAllSubProjectList({}).then(response => {
      if (response.code === 1) {
        console.log(response);
        this.setData({ subprojectList: response.data });
      } else {
        console.error('Failed to fetch project list');
      }
    }).catch(error => {
      console.error('Error fetching project list:', error);
    });
  },

  // 项目选择器变化时调用
  onProjectChange(e) {
    const selectedProjectId = this.data.subprojectList[e.detail.value].id;
    const selectedProjectName = this.data.subprojectList[e.detail.value].name;
    this.setData({ selectedProjectId, selectedProjectName }, () => {
      this.loadEmployeeList(selectedProjectId);
    });
  },

  // 加载员工列表
  loadEmployeeList(selectedProjectId) {
    fetchSubProjectEmployees(selectedProjectId).then(response => {
      if (response.code === 1) {
        console.log(response.data);
        const allEmployees = response.data.map(item => ({
          name: item.name,
          id: item.employeeId,
          inContainer: false
        }));
        this.setData({ allEmployees });
        this.updateStaffList();
      } else {
        console.error('Failed to fetch employee list');
      }
    }).catch(error => {
      console.error('Error fetching employee list:', error);
    });
  },

  // 更新已选择的员工列表
  updateStaffList() {
    const staffList = this.data.allEmployees.filter(employee => employee.inContainer);
    this.setData({ staffList });
  },

  // 日期选择器变化时调用
  bindDateChange(e) {
    this.setData({
      date: e.detail.value,
    });
  },

  // 打开添加员工弹窗
  openAddModal() {
    if (!this.data.date || !this.data.selectedProjectId) {
      wx.showToast({
        title: '请先选择日期和项目',
        icon: 'none'
      });
      return;
    }
    this.setData({ showAddModal: true });
  },

  // 关闭添加员工弹窗
  closeAddModal() {
    this.setData({ showAddModal: false });
  },

  // 打开删除员工弹窗
  openRemoveModal() {
    this.setData({ showRemoveModal: true });
  },

  // 关闭删除员工弹窗
  closeRemoveModal() {
    this.setData({ showRemoveModal: false });
  },

  // 添加员工到已选择列表
  addStaff(e) {
    const name = e.currentTarget.dataset.name;
    const allEmployees = this.data.allEmployees.map(employee => {
      if (employee.name === name) {
        employee.inContainer = true;
      }
      return employee;
    });
    this.setData({ allEmployees });
  },

  // 从已选择列表中删除员工
  removeStaffInModal(e) {
    const name = e.currentTarget.dataset.name;
    const allEmployees = this.data.allEmployees.map(employee => {
      if (employee.name === name) {
        employee.inContainer = false;
      }
      return employee;
    });
    this.setData({ allEmployees });
    this.updateStaffList();
  },

  // 确认添加员工
  confirmAdd() {
    this.updateStaffList();
    this.closeAddModal();
  },

  // 确认删除员工
  confirmRemove() {
    this.updateStaffList();
    this.closeRemoveModal();
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      tabActive: tab
    });
  },

  // 选择班次
  selectShift(e) {
    const shift = e.currentTarget.dataset.shift;
    this.setData({
      shift
    });
  },

  // 选择加班状态
  selectOvertime(e) {
    const overtime = e.currentTarget.dataset.overtime;
    this.setData({
      overtime,
      overtimeHours: ''
    });
  },

  // 输入加班时长
  inputOvertime(e) {
    this.setData({
      overtimeHours: e.detail.value
    });
  },

  // 输入备注
  inputRemark(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  // 格式化日期
  formatDate(date) {
    const d = new Date(date);
    const month = `${d.getMonth() + 1}`.padStart(2, '0');
    const day = `${d.getDate()}`.padStart(2, '0');
    const year = d.getFullYear();
    return [year, month, day].join('-');
  },

  // 提交考勤
  submitAttendance() {
    const recordedList = this.data.staffList.map(item => ({
      name: item.name,
      id: item.id,
      shift: this.data.shift,
      overtime: this.data.overtime === '无加班' ? this.data.overtime : this.data.overtimeHours + '小时',
      remark: this.data.remark
    }));

    const employeeIds = recordedList.map(item => item.id);
    const workingTime = this.data.shift === '全天' ? 1 : (this.data.shift === '上午' || this.data.shift === '下午' ? 0.5 : 0);
    const overTime = this.data.overtime === '无加班' ? 0 : this.data.overtimeHours;

    const date = this.formatDate(this.data.date);

    console.log('提交的考勤数据:', {
      time: date,
      employeeIds: employeeIds,
      workingTime: workingTime,
      overTime: overTime,
      projectId: this.data.selectedProjectId,
      remark: this.data.remark
    });

    addAttendance({
      time: date,
      employeeIds: employeeIds,
      workingTime: workingTime,
      overTime: overTime,
      projectId: this.data.selectedProjectId,
      remark: this.data.remark
    }).then(res => {
      console.log('提交成功', res);
    }).catch(err => {
      console.log('提交失败', err);
    });

    this.setData({
      recordedList,
      shift: '',
      overtime: '无加班',
      overtimeHours: '',
      remark: ''
    });
  }
});